package se.joakimback.decorator.renderer;

import java.awt.image.BufferedImage;

import se.joakimback.decorator.support.ImageUtils;
import se.joakimback.decorator.view.Workspace;

public class RenderManager {
	class RenderRunnable implements Runnable {
		private boolean hasRequest;

		public void request() {
			Renderer.getSingleton().cancel();
			
			hasRequest = true;
		}

		@Override
		public void run() {
			try {
				while (true) {
					if (hasRequest) {
						hasRequest = false;

						Workspace vWorkspace = Workspace.getSingleton();
						 
						BufferedImage vImage = ImageUtils.clone(
								vWorkspace.getBaseImage());
						
						Renderer.getSingleton().render(vImage, 
								vWorkspace.getLayers());
					}

					Thread.sleep(10);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private static RenderManager sSINGLETON = new RenderManager();

	public static RenderManager getSingleton() {
		return sSINGLETON;
	}

	private RenderRunnable mRenderRunnable;

	protected RenderManager() {
		mRenderRunnable = new RenderRunnable();

		new Thread(mRenderRunnable).start();
	}

	public void request() {
		mRenderRunnable.request();
	}
}
